﻿/*
 * 创建人:lf
 * 创建时间:2021/5/20 10:25:15
 * 描述:
 * */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Furion.JsonSerialization;

using MapsterMapper;

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

using Purchasing.Application.Dtos;
using Purchasing.Core; 

using static Microsoft.Extensions.Logging.EventSource.LoggingEventSource;

namespace Purchasing.Web.Core
{

    public interface ICompany
    {
        Task<string> GetAll(string keyword);
    }

    public class CompanyService : ICompany ,ITransient
    {
        private readonly ILogger<CompanyService> _logger;
        private readonly IRepository<HrmSubCompany> _repository;
        private readonly IMapper _mapper;
        private readonly IJsonSerializerProvider _jsonSerializer;

        public CompanyService(ILogger<CompanyService> logger, IRepository<HrmSubCompany> repository, IMapper mapper, IJsonSerializerProvider jsonSerializer)  
        {
            this._logger = logger;
            this._repository = repository;
            this._mapper = mapper;
            this._jsonSerializer = jsonSerializer;
        }

        public async Task<string> GetAll(string keyword)
        {
            //动态修改仓储模式(只读)
            var readRepository = _repository.Constraint<IReadableRepository<HrmSubCompany>>();
            //查询所有数据
            //var list = await readRepository.AsQueryable().ToListAsync();
            var list = await readRepository.Where(!string.IsNullOrWhiteSpace(keyword), o => o.Subcompanyname.Contains(keyword)).ToListAsync();
            _logger.LogInformation("获得了HrmSubCompany表的所有数据");

            var dtos = _mapper.Map<List<CompanyDto>>(list);
            _logger.LogInformation("数据已经格式化"); 

            return _jsonSerializer.Serialize(dtos);
        }
    }
}
